package com.zhs.gccs.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.AppUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.umeng.message.PushAgent;
import com.zhs.gccs.R;
import com.zhs.gccs.activity.app.AppVersionActivity;
import com.zhs.gccs.base.BaseActivity;
import com.zhs.gccs.fragment.BaseFragment;
import com.zhs.gccs.fragment.main.WorkTableFragment;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.model.AppVersionBean;
import com.zhs.gccs.service.UploadFileService;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.GsonImpl;
import com.zhs.gccs.utils.PackageUtil;
import com.zhs.gccs.utils.PermissionListener;
import com.zhs.gccs.utils.SharedPrefHelper;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.view.taskMap.LeftMenuView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

public class DrawerMainActivity extends BaseActivity {
    @BindView(R.id.fl_content)
    FrameLayout fl_content;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer_layout;
    @BindView(R.id.leftMenuView)
    LeftMenuView leftMenuView;
    public static void start(Context context) {
        context.startActivity(new Intent(context, DrawerMainActivity.class));
    }

    @Override
    public void onBackPressed() {
        //防止用户不注意退出
    }

    //上次按下返回键的系统时间
    private long lastBackTime = 0;
    //当前按下返回键的系统时间
    private long currentBackTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //捕获返回键按下的事件
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //获取当前系统时间的毫秒数
            currentBackTime = System.currentTimeMillis();
            //比较上次按下返回键和当前按下返回键的时间差，如果大于2秒，则提示再按一次退出
            if (currentBackTime - lastBackTime > 2 * 1000) {
                ToastUtils.toast("再按一次返回键退出");
                lastBackTime = currentBackTime;
            } else { //如果两次按下的时间差小于2秒，则退出程序
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_drawer);
        ImmersionBar.with(this).statusBarDarkFont(false).init();
//        ImmersionBar.with(this).init();
        ButterKnife.bind(this);
//        fl_content.setPadding(0, ImmersionBar.getStatusBarHeight(this), 0, 0);
        //应用活跃统计
        PushAgent.getInstance(this).onAppStart();
        leftMenuView.setDrawerLayout(drawer_layout);
        leftMenuView.setUserName(SharedPrefHelper.getInstance().getUserNickName());
        leftMenuView.setUserDept(SharedPrefHelper.getInstance().getUserOrgName());
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        BaseFragment workTableFragment = WorkTableFragment.newInstance();
        transaction.replace(R.id.fl_content, workTableFragment);
        transaction.commit();
        checkPermission();
        Intent intent = new Intent(context, UploadFileService.class);
        startService(intent);
    }



    void checkPermission() {
        requestPermission(context, new PermissionListener() {
                    @Override
                    public void onSucceed() {
                        checkAppVersion();
                    }

                    @Override
                    public void onFailed() {
                        checkPermission();
                    }
                }, PermissionConstants.STORAGE,
                PermissionConstants.LOCATION,
                PermissionConstants.CAMERA,
                PermissionConstants.MICROPHONE);
    }

    private void checkAppVersion() {
        Map data = new HashMap();
        try {
            data.put("packageName", PackageUtil.getPackageName(context));
        } catch (Exception e) {
        }
        RequestBody requestBody = createRequestBody(data);
        toSubscribeSingleOb(Api.getDefault().appLatestVersion2(requestBody),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        AppVersionBean bean = GsonImpl.get().toObject(result, AppVersionBean.class);
                        if (bean != null && bean.getCode() == 200
                                && bean.getData() != null && bean.getData().getAppVersionCode() != null) {
                            int appVersionCode = AppUtils.getAppVersionCode();
                            if (appVersionCode < bean.getData().getAppVersionCode()) {
                                DialogUtils.showPromote2(context, "核查APP有新版本可以更新了", null, new DialogUtils.OnConfirmListener() {
                                    @Override
                                    public void onConfirmed() {
                                        Intent intent = new Intent(context, AppVersionActivity.class);
                                        startActivity(intent);
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    protected void _onError(String result) {
                        Log.d("_onError", "_onError");
                    }
                });
    }

    void toLogin() {
        Intent intent = new Intent(context, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    public void openDrawer() {
        drawer_layout.openDrawer(GravityCompat.START);
    }
}
